#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
HLS服务
管理HLS流和播放列表
"""

import os
import json
from typing import Dict, Any, Optional, List
from datetime import datetime, timedelta

from app.core.database import SessionLocal
from app.models.stream import Stream


class HLSService:
    """HLS服务"""
    
    def __init__(self):
        self.hls_path = "/app/recordings/hls"
        
    def get_playlist(self, stream_id: str) -> Optional[str]:
        """获取播放列表"""
        playlist_path = os.path.join(self.hls_path, stream_id, "playlist.m3u8")
        
        if not os.path.exists(playlist_path):
            return None
            
        try:
            with open(playlist_path, 'r', encoding='utf-8') as f:
                return f.read()
        except Exception:
            return None
            
    def get_segment(self, stream_id: str, segment_name: str) -> Optional[bytes]:
        """获取分片"""
        segment_path = os.path.join(self.hls_path, stream_id, segment_name)
        
        if not os.path.exists(segment_path):
            return None
            
        try:
            with open(segment_path, 'rb') as f:
                return f.read()
        except Exception:
            return None
            
    def get_stream_info(self, stream_id: str) -> Dict[str, Any]:
        """获取流信息"""
        info_path = os.path.join(self.hls_path, stream_id, "info.json")
        
        if not os.path.exists(info_path):
            return {}
            
        try:
            with open(info_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception:
            return {}
            
    def list_streams(self) -> List[str]:
        """列出所有HLS流"""
        if not os.path.exists(self.hls_path):
            return []
            
        streams = []
        for item in os.listdir(self.hls_path):
            if os.path.isdir(os.path.join(self.hls_path, item)):
                streams.append(item)
                
        return streams
        
    def get_stream_status(self, stream_id: str) -> Dict[str, Any]:
        """获取流状态"""
        playlist_path = os.path.join(self.hls_path, stream_id, "playlist.m3u8")
        
        if not os.path.exists(playlist_path):
            return {"status": "offline", "segments": 0}
            
        try:
            with open(playlist_path, 'r', encoding='utf-8') as f:
                content = f.read()
                
            segments = [line for line in content.split('\n') if line.endswith('.ts')]
            
            return {
                "status": "online",
                "segments": len(segments),
                "last_update": datetime.fromtimestamp(
                    os.path.getmtime(playlist_path)
                ).isoformat()
            }
        except Exception:
            return {"status": "offline", "segments": 0}


# 全局HLS服务实例
_hls_service = None

def get_hls_service():
    """获取HLS服务实例"""
    global _hls_service
    if _hls_service is None:
        _hls_service = HLSService()
    return _hls_service